from datetime import datetime
from typing import Dict, Any, Optional

from config.logging_config import get_logger

logger = get_logger(__name__)


class SendResponseDTO:
    """统一的响应消息处理类，提供通用的流式消息创建和处理方法"""

    @staticmethod
    def create_stream_message(message_type: str, content: str, stage: str,
                              status: str = "completed") -> Dict[str, Any]:
        """创建标准格式的流式消息"""
        return {
            "type": message_type,
            "content": content,
            "timestamp": datetime.now().isoformat(),
            "data": {
                "stage": stage,
                "status": status
            }
        }

    @staticmethod
    def create_simple_message(message_type: str, content: str, data: Dict[str, Any] = None) -> Dict[str, Any]:
        """创建简单格式的流式消息"""
        message = {
            "type": message_type,
            "content": content,
            "timestamp": datetime.now().isoformat()
        }
        if data:
            message["data"] = data
        return message

    @staticmethod
    def create_error_message(error_msg: str, stage: str = "processing") -> Dict[str, Any]:
        """创建错误消息"""
        return SendResponseDTO.create_stream_message(
            "error", error_msg, stage, status="failed"
        )

    @staticmethod
    def create_thinking_message(message: str, stage: str = "thinking") -> Dict[str, Any]:
        """创建思考过程消息"""
        return SendResponseDTO.create_stream_message(
            "thinking", message, stage, status="processing"
        )

    @staticmethod
    def create_tool_message(tool_name: str, content: str, result: Any = None,
                            stage: str = "tool_execution") -> Dict[str, Any]:
        """创建工具调用消息"""
        data = {
            "tool_name": tool_name,
            "stage": stage,
            "status": "completed" if result is not None else "processing"
        }
        if result is not None:
            data["tool_result"] = result

        return {
            "type": "tool",
            "content": content,
            "timestamp": datetime.now().isoformat(),
            "data": data
        }

    @staticmethod
    def create_rag_message(query: str, content: str, results: Any = None,
                           count: int = 0, stage: str = "rag_search") -> Dict[str, Any]:
        """创建RAG检索消息"""
        data = {
            "query": query,
            "count": count,
            "stage": stage,
            "status": "completed" if results is not None else "processing"
        }
        if results is not None:
            data["rag_results"] = results

        return {
            "type": "rag",
            "content": content,
            "timestamp": datetime.now().isoformat(),
            "data": data
        }

    @staticmethod
    def create_mcp_message(server_name: str, tool_name: str, content: str,
                           result: Any = None, stage: str = "mcp_execution") -> Dict[str, Any]:
        """创建MCP接口消息"""
        data = {
            "server_name": server_name,
            "tool_name": tool_name,
            "stage": stage,
            "status": "completed" if result is not None else "processing"
        }
        if result is not None:
            data["mcp_result"] = result

        return {
            "type": "mcp",
            "content": content,
            "timestamp": datetime.now().isoformat(),
            "data": data
        }

    @staticmethod
    def create_final_result_message(success: bool, response: str, agent_name: str,
                                    error: Optional[str] = None) -> Dict[str, Any]:
        """创建最终结果消息"""
        data = {
            "success": success,
            "response": response,
            "agent_name": agent_name
        }
        if error:
            data["error"] = error

        # 直接创建消息格式，避免嵌套
        return {
            "type": "final_result",
            "content": response,
            "timestamp": datetime.now().isoformat(),
            "data": data
        }

    @staticmethod
    def create_human_interaction_message(query: str, tool_info: Dict[str, Any],
                                         interaction_type: str = "tool_confirmation",
                                         interaction_id: str = None) -> Dict[str, Any]:
        """创建人机交互消息 - 统一格式"""

        # 如果没有提供interaction_id，自动生成一个
        if not interaction_id:
            interaction_id = f"interaction_{int(datetime.now().timestamp() * 1000)}"

        # 确保tool_info包含interaction_id
        if isinstance(tool_info, dict):
            tool_info["interaction_id"] = interaction_id

        return {
            "type": "human_interaction",
            "content": query,
            "timestamp": datetime.now().isoformat(),
            "data": {
                "interaction_id": interaction_id,
                "interaction_type": interaction_type,
                "tool_info": tool_info,
                "query": query,
                "responded": False,
                "responding": False,
                "approved": None,
                "stage": "human_confirmation",
                "status": "waiting"
            }
        }

    @staticmethod
    def create_node_update_message(node_type: str, base_content: str, node_result: Any = None,
                                   stage: str = "processing", tool_name: str = None,
                                   server_name: str = None, query: str = None, count: int = 0) -> Dict[str, Any]:
        """
        统一处理节点更新消息，根据节点类型分发到具体的消息创建方法
        
        Args:
            node_type: 节点类型 ('execute_tools', 'execute_mcp', 'execute_rag', 'think')
            base_content: 基础提示内容 (如: "正在思考下一步行动...")
            node_result: 节点执行结果
            stage: 执行阶段
            tool_name: 工具名称（用于tool和mcp类型）
            server_name: 服务名称（用于mcp类型）
            query: 查询内容（用于rag类型）
            count: 结果数量（用于rag类型）
        """
        # 构建完整的内容，包含基础提示和结果展示
        full_content = base_content

        # 根据节点类型分发到具体的消息创建方法
        if node_type == "execute_tools":
            return SendResponseDTO.create_tool_message(
                tool_name=tool_name or '未知工具',
                content=full_content,
                result=node_result.get('tool_results') if isinstance(node_result, dict) else node_result,
                stage=stage
            )
        elif node_type == "execute_mcp":
            return SendResponseDTO.create_mcp_message(
                server_name=server_name or '未知服务',
                tool_name=tool_name or '未知工具',
                content=full_content,
                result=node_result.get('mcp_results') if isinstance(node_result, dict) else node_result,
                stage=stage
            )
        elif node_type == "execute_rag":
            return SendResponseDTO.create_rag_message(
                query=query or '未知查询',
                content=full_content,
                results=node_result.get('rag_results') if isinstance(node_result, dict) else None,
                count=count,
                stage=stage
            )
        elif node_type == "think":
            return SendResponseDTO.create_thinking_message(
                message=full_content,
                stage=stage
            )
        else:
            # 默认创建普通消息
            return SendResponseDTO.create_simple_message(
                message_type="message",
                content=full_content,
                data={
                    "node_type": node_type,
                    "stage": stage,
                    "node_result": node_result
                }
            )
